<div data-title="Device File Manager" style="height: 100%;">
    <div class="col-xs-3 main-left-column">
      <div class="list-group upcontrol" id="file-list" style="padding: 0; margin: 0; top: 5px;"></div>
    </div>
    <div class="col-xs-9 main-right-column">
      <div class="editor-navbar">
        <button class="btn btn-sm btn-success file-control" id="file-refresh-button"><i class="fa fa-refresh"></i> Refresh File List</button>
        <button class="btn btn-sm btn-success file-control" id="file-save-button"><i class="fa fa-save"></i> Save File</button>
        <button class="btn btn-sm btn-success file-control" id="file-savereboot-button"><i class="fa fa-retweet"></i> Save + Reboot</button>
<!-- 
        &nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;
        <div style="position: relative; display: inline-block;">
          <button class="btn btn-sm btn-info file-control dropdown-toggle" id="share-button"
            data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
            <i class="fa fa-share"></i>
            Share File
            <span class="caret"></span>          
          </button>

          <div class="dropdown-menu" style="background: #fcfcfc;">
            <form class="form" style="padding: 1em;" id="share-form">

              <div class="input-group">
                <span class="input-group-addon"><i class="fa fa-user"></i></span>
                <input required id="share-author-input" placeholder="Your Name (required)" class="form-control" type="text">
              </div>

              <div class="input-group">
                <span class="input-group-addon"><i class="fa fa-list-alt"></i></span>
                <input required id="share-title-input" placeholder="Snippet Title (required)" class="form-control" type="text">
              </div>

              <button id="publish-button" style="position: relative;"
                class="btn btn-success btn-block disabled form-control"
                id="publish-button" type="button">
                <i class="fa fa-share"></i>
                Publish code and device info to mongoose-os.com/snippets.html
              </button>
              <p class="hidden" style="margin-top: 1em;">
                Snippet URL: <a target="_blank" id="share-id"></a>
              </p>
              <p style="margin-top: 1em;">See all published snippets at
              <a href="https://mongoose-os.com/snippets.html"
                target="_blank">mongoose-os.com/snippets.html</a></p>
            </form>

          </div>
        </div>
 -->
      </div>
      <div class="form-group upcontrol">
        <div id="device_file_editor" class="editor"></div>
      </div>
    </div>
</div>

<script>
  var file_editor = mkeditor('device_file_editor');
  $(document).off('click', '.file');
  $(document).on('click', '.file', function(ev) {
    var $t = $(ev.target).closest('.file');
    var name = $t.attr('rel');
    $.ajax({url: '/get', data: {name: name}}).done(function(json) {
      $('.file').removeClass('selected');
      $t.addClass('selected');
      file_editor.lang = guesslang(name);
      file_editor.setValue(json.result || '', -1);
      file_editor.session.setMode('ace/mode/' + file_editor.lang);
      file_editor.loadSnippets();

      addLog('Loaded ' + name + '\n');
    });
    return false;
  });

  var onSave = function() {
    var fileName = $('.file.selected').attr('rel');
    var text = file_editor.getValue();
    return $.ajax({url: '/put', data: {data: text, path: fileName}}).then(function() {
      addLog('Saved ' + fileName + '\n');
    });
  };

  $(document).off('click', '#file-save-button');
  $(document).on('click', '#file-save-button', onSave);

  $(document).off('click', '#file-savereboot-button');
  $(document).on('click', '#file-savereboot-button', function () {
    onSave().then(function() {
      return $.ajax({url: '/call', data: {method: 'Sys.Reboot'}});
    }).then(function() {
      addLog('Device reboot successful\n');
    });
  });

  $(document).on('keyup paste', '#share-form', function(ev) {
    var author = $('#share-author-input').val() || '';
    var title = $('#share-title-input').val() || '';
    var enableShare = !author.match(/^\s*$/) && !title.match(/^\s*$/);
    $('#publish-button').toggleClass('disabled', !enableShare);
    if (enableShare && ev.target.id == 'share-title-input' && ev.keyCode == 13) {
      $('#publish-button').trigger('click');
    }
  });

  var onPublish = function(ev) {
    var backendAddr = 'https://mongoose-os.com';
    // var backendAddr = 'http://127.0.0.1:8000';
    var t = $('#publish-button').addClass('disabled');
    var failreq = function(err) {
      t.removeClass('disabled');
      new PNotify({title: err || 'Error creating snippet', type: 'error' });
    };
    var data = {
      file_name: $('.file.selected').attr('rel'),
      snippet_text: file_editor.getValue(),
      title: $('#share-title-input').val(),
      author: $('#share-author-input').val(),
    };
    if (!data.file_name || !data.snippet_text) {
      return failreq('Please select a non-empty file'); 
    }
    $.ajax({url: '/call', data: {method: 'Sys.GetInfo'}}).then(function(r) {
      data.fwinfo = r.result;
      return $.ajax({
        url: backendAddr + '/snippets/add',
        crossDomain: true,
        method: 'POST',
        dataType: 'json',
        data: data
      });
    }).then(function(res) {
      t.removeClass('spinner disabled');
      if (res.error) {
        return failreq(res.error);
      } else {
        var href = backendAddr + '/snippets.html?' + res.id;
        $('#share-id').html(href).attr({href: href}).parent().removeClass('hidden');
        $('#share-title-input').val('')
        $('#share-form').trigger('keyup');
        addLog('Snippet saved\n');
      }
    }).fail(function(err) {
      failreq(err);
    });
    return false;
  };

  $(document).off('submit', '#share-form');
  $(document).off('click', '#publish-button');
  $(document).on('submit', '#share-form', onPublish);
  $(document).on('click', '#publish-button', function() {
    $('#share-form').submit();
    return false;
  });

  var refreshFileList = function() {
    var selectedFile = $('.file.selected').attr('rel');
    return $.ajax({url: '/call', data: {method: 'FS.ListExt', timeout: 15}}).done(function(json) {
      var $tbody = $('#file-list').empty();
      json.result.sort(function(a, b) {
        if (a.name.match(/jsc$/) && b.name.match(/jsc$/)) return a.name > b.name ? 1 : -1;
        if (a.name.match(/jsc$/)) return 1;
        if (b.name.match(/jsc$/)) return -1;
        if (a.name.match(/^api_/) && b.name.match(/^api_/)) return a.name > b.name ? 1 : -1;
        if (a.name.match(/^api_/)) return 1;
        if (b.name.match(/^api_/)) return -1;
        return a.name > b.name ? 1 : -1;
      });
      $.each(json.result, function(i, v) {
        var sizeSpan = $('<span class="pull-right file-size"/>').text(v.size);
        var nameSpan = $('<span class="file-name"/>').text(v.name);
        var link = $('<a href="#" class="list-group-item file"/>')
            .attr({rel: v.name})
            .append(sizeSpan)
            .append(nameSpan)
            .addClass(v.name === 'init.js' ? 'is_init' : '')
            .addClass(v.name.match(/\.js$/) ? 'is_js' : '')
            .addClass(v.name.match(/\.jsc$/) ? 'is_jsc' : '')
            .addClass(v.name.match(/\.json$/) ? 'is_json' : '')
            .addClass(v.name.match(/^api_/) ? 'is_api' : '')
            .appendTo($tbody);
      });
      file_editor.setValue('', -1);
    }).always(function() {
      // Open init.js automatically if no file is opened
      $('.file[rel="' + (selectedFile || 'init.js') + '"]').trigger('click');
    });
  };
  $(document).off('click', '#file-refresh-button');
  $(document).on('click', '#file-refresh-button', refreshFileList);
</script>
